package com.springcloud.sc.ucpv5.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springcloud.sc.ucp.v5.api.entity.UcpVoipVoice;
import com.springcloud.sc.ucp.v5.api.vo.UcpVoipVoiceVo;
import com.springcloud.sc.ucpv5.client.commondata.MyUser;
import com.springcloud.sc.ucpv5.client.module.datamanager.BaseDataManager;
import com.springcloud.sc.ucpv5.mapper.UcpVoipVoiceMapper;
import com.springcloud.sc.ucpv5.service.UcpVoipVoiceRecordService;
import com.springcloud.sc.ucpv5.service.UcpVoipVoiceService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.jms.Topic;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;

@Slf4j
@Service
@AllArgsConstructor
public class UcpVoipVoiceServiceImpl extends ServiceImpl<UcpVoipVoiceMapper, UcpVoipVoice> implements UcpVoipVoiceService {

    @Autowired
    private UcpVoipVoiceMapper ucpVoipVoiceMapper;

    @Autowired
    private UcpVoipVoiceRecordService ucpVoipVoiceRecordService;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Resource(name = "topic")
    private Topic topic;

    @Transactional
    public Integer saveUcpVoipVoice(UcpVoipVoiceVo ucpVoipVoiceVo) {

        String uuid = ucpVoipVoiceVo.getUuid();
        String uuid_branch = null;
        if(uuid.indexOf("_")>0){
            uuid_branch = uuid.split("_")[0];
        }
        //不分段
        if (uuid_branch == null ){
            return saveUcpVoipVoiceNoBranch(ucpVoipVoiceVo);
        }else{
            //分段处理
            return saveUcpVoipVoiceBranch(ucpVoipVoiceVo);
        }
    }

    @Transactional
    public Integer  saveUcpVoipVoiceNoBranch(UcpVoipVoiceVo ucpVoipVoiceVo){
        List<UcpVoipVoice> ucpVoipVoiceList = ucpVoipVoiceMapper.getEntityByUuid( ucpVoipVoiceVo.getUuid() );
        UcpVoipVoice ucpVoipVoice = null;
        if(!ucpVoipVoiceList.isEmpty()){
            ucpVoipVoice =  ucpVoipVoiceList.get(0);
        }
        if(ucpVoipVoice == null ){
            ucpVoipVoice = new UcpVoipVoice();
        }
        BeanUtils.copyProperties(ucpVoipVoiceVo, ucpVoipVoice);
        ucpVoipVoice.setSuccessSum(ucpVoipVoiceVo.getSuccessSum() );
        ucpVoipVoice.setFailedSum( ucpVoipVoiceVo.getFailedSum() );
        ucpVoipVoice.setGroupList( ucpVoipVoiceVo.getGroupList() );

        LocalTime localTime = LocalTime.now();
        LocalDate localDate = LocalDate.now();
        ucpVoipVoice.setCreateTime( localDate.toString() +" "+localTime.toString() );

        // 20190524 wsy 增加用户描述
        try{
            MyUser user = BaseDataManager.getInstance().userGet(ucpVoipVoice.getPromulgator());
            if(user != null){
                ucpVoipVoice.setPromulgatorName(user.getIdlData().getDesc());
            }
            else{
                ucpVoipVoice.setPromulgatorName(ucpVoipVoice.getPromulgator());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        if(ucpVoipVoiceList.isEmpty()){
            return ucpVoipVoiceMapper.insert( ucpVoipVoice );
        }else{
            return ucpVoipVoiceMapper.updateByEntity( ucpVoipVoice );
        }
    }

    /**
     * 分包来发送语音记录
     * @param ucpVoipVoiceVo
     * @return
     */
    public Integer saveUcpVoipVoiceBranch(UcpVoipVoiceVo ucpVoipVoiceVo){

        String uuid = ucpVoipVoiceVo.getUuid();
        String uuid_branch = null;

        if(uuid.indexOf("_")>0){
            uuid_branch = uuid.split("_")[0];
        }
        /**
         * 1、
         * UUID分包的情况：
         * 先判断是否有分段，如果有，取分段记录及没有分段的数据记录
         *
         * 第一次分包进来，两个对象都为空，这时需要将两个包进行保存，只进行保存
         * 第二次分包进来，
         */
        List<UcpVoipVoice> ucpVoipVoiceList = ucpVoipVoiceMapper.getEntityByUuid( ucpVoipVoiceVo.getUuid() );
        List<UcpVoipVoice> ucpVoipVoiceBranchList = null;
        UcpVoipVoice ucpVoipVoiceBranch = null;
        if( uuid_branch!=null ){
            ucpVoipVoiceBranchList = ucpVoipVoiceMapper.getEntityByUuid( uuid_branch );
            if(ucpVoipVoiceBranchList!=null && !ucpVoipVoiceBranchList.isEmpty()){
                ucpVoipVoiceBranch =  ucpVoipVoiceBranchList.get(0);
            }
        }
        UcpVoipVoice ucpVoipVoice = null;
        if(!ucpVoipVoiceList.isEmpty()){
            ucpVoipVoice =  ucpVoipVoiceList.get(0);
        }

        LocalTime localTime = LocalTime.now();
        LocalDate localDate = LocalDate.now();
        //第一次进来时，两个对象都为空,这时需要将两个包进行保存
        if(ucpVoipVoiceBranch == null && ucpVoipVoice == null){
            ucpVoipVoice = new UcpVoipVoice();
            ucpVoipVoiceBranch = new UcpVoipVoice();
            BeanUtils.copyProperties(ucpVoipVoiceVo, ucpVoipVoice);
            BeanUtils.copyProperties(ucpVoipVoiceVo, ucpVoipVoiceBranch);
            ucpVoipVoice.setSuccessSum(ucpVoipVoiceVo.getSuccessSum() );
            ucpVoipVoice.setFailedSum( ucpVoipVoiceVo.getFailedSum() );
            ucpVoipVoice.setGroupList( ucpVoipVoiceVo.getGroupList() );
            ucpVoipVoiceBranch.setSuccessSum(ucpVoipVoiceVo.getSuccessSum() );
            ucpVoipVoiceBranch.setFailedSum( ucpVoipVoiceVo.getFailedSum() );
            ucpVoipVoiceBranch.setGroupList( ucpVoipVoiceVo.getGroupList() );
            ucpVoipVoice.setCreateTime( localDate.toString() +" "+localTime.toString() );
            ucpVoipVoiceBranch.setCreateTime( localDate.toString() +" "+localTime.toString() );
            ucpVoipVoiceBranch.setUuid( uuid_branch );

            // 20190524 wsy 增加用户描述
            try{
                MyUser user = BaseDataManager.getInstance().userGet(ucpVoipVoiceBranch.getPromulgator());
                if(user != null){
                    ucpVoipVoiceBranch.setPromulgatorName(user.getIdlData().getDesc());
                    ucpVoipVoice.setPromulgatorName(user.getIdlData().getDesc());
                }
                else{
                    ucpVoipVoiceBranch.setPromulgatorName(ucpVoipVoiceBranch.getPromulgator());
                    ucpVoipVoice.setPromulgatorName(ucpVoipVoice.getPromulgator());
                }
            }catch(Exception e){
                e.printStackTrace();
            }

            ucpVoipVoiceMapper.insert( ucpVoipVoice );
            return ucpVoipVoiceMapper.insert( ucpVoipVoiceBranch );

        }else if(ucpVoipVoiceBranch!=null && ucpVoipVoice == null){
            ucpVoipVoice = new UcpVoipVoice();
            BeanUtils.copyProperties(ucpVoipVoiceVo, ucpVoipVoice);
            //第二次进来时，拆分后的对象一定是有数据的，另外一个未拆分的数据进行合并
            ucpVoipVoice.setSuccessSum(ucpVoipVoiceVo.getSuccessSum() );
            ucpVoipVoice.setFailedSum( ucpVoipVoiceVo.getFailedSum() );
            ucpVoipVoice.setGroupList( ucpVoipVoiceVo.getGroupList() );
            Integer successSum = ucpVoipVoiceBranch.getSuccessSum()+ucpVoipVoiceVo.getSuccessSum();
            ucpVoipVoiceBranch.setSuccessSum( successSum );
            Integer failedSum = ucpVoipVoiceBranch.getFailedSum() + ucpVoipVoiceVo.getFailedSum();
            ucpVoipVoiceBranch.setFailedSum( failedSum );
            //groupList 的添加
            ucpVoipVoiceBranch.setGroupList( ucpVoipVoiceVo.getGroupList() );
            String calledBranchNumbers = ucpVoipVoiceBranch.getCalledNumbers();
            String calledNumbers = ucpVoipVoiceVo.getCalledNumbers();
            String[] branchNumbers = new String[]{};
            String[] numbers = new String[]{};
            if(calledBranchNumbers!=null){
                branchNumbers = calledBranchNumbers.split(",");
            }
            if(calledNumbers!=null){
                numbers = calledNumbers.split(",");
            }
            String[] newStr = new String[branchNumbers.length+numbers.length];
            int index = 0;
            for(int x=0;x<branchNumbers.length;x++){
                newStr[x] = branchNumbers[x];
                index = x+1;
            }
            boolean branchBool = false;
            for(int i = 0 ; i<numbers.length; i++){
                for(int j = 0 ; j< branchNumbers.length ; j++){
                    if(branchNumbers[j].equals( numbers[i]) ){
                        branchBool = true;
                        break;
                    }
                }
                //表示没有找到
                if(branchBool == false){
                    newStr[index] = numbers[i];
                    index++;
                    branchBool = true;
                }else{
                    branchBool = false;
                }
            }
            StringBuffer bfs = new StringBuffer();
            for(String nstr : newStr ){
                if(bfs.length() >0 ){
                    if(nstr!=null && !nstr.equals("null")){
                        bfs.append(","+nstr);
                    }
                }else{
                    bfs.append(nstr);
                }
            }
            ucpVoipVoiceBranch.setCalledNumbers( bfs.toString() );
            ucpVoipVoiceMapper.insert( ucpVoipVoice );
            return ucpVoipVoiceMapper.updateByEntity( ucpVoipVoiceBranch );

        }else{

            //第二次进来时，拆分后的对象一定是有数据的，另外一个未拆分的数据进行合并
            ucpVoipVoice.setSuccessSum(ucpVoipVoiceVo.getSuccessSum() );
            ucpVoipVoice.setFailedSum( ucpVoipVoiceVo.getFailedSum() );
            ucpVoipVoice.setGroupList( ucpVoipVoiceVo.getGroupList() );
            Integer successSum = ucpVoipVoiceBranch.getSuccessSum()+ucpVoipVoiceVo.getSuccessSum();
            ucpVoipVoiceBranch.setSuccessSum( successSum );
            Integer failedSum = ucpVoipVoiceBranch.getFailedSum() + ucpVoipVoiceVo.getFailedSum();
            ucpVoipVoiceBranch.setFailedSum( failedSum );

            //groupList 的添加
            ucpVoipVoiceBranch.setGroupList( ucpVoipVoiceVo.getGroupList() );
            String calledBranchNumbers = ucpVoipVoiceBranch.getCalledNumbers();
            String calledNumbers = ucpVoipVoiceVo.getCalledNumbers();
            String[] branchNumbers = new String[]{};
            String[] numbers = new String[]{};
            if(calledBranchNumbers!=null){
                branchNumbers = calledBranchNumbers.split(",");
            }
            if(calledNumbers!=null){
                numbers = calledNumbers.split(",");
            }
            String[] newStr = new String[branchNumbers.length+numbers.length];

            int index = 0;
            for(int x=0;x<branchNumbers.length;x++){
                newStr[x] = branchNumbers[x];
                index = x+1;
            }
            boolean branchBool = false;
            for(int i = 0 ; i<numbers.length; i++){
                for(int j = 0 ; j< branchNumbers.length ; j++){
                    if(branchNumbers[j].equals( numbers[i]) ){
                        branchBool = true;
                        break;
                    }
                }
                //表示没有找到
                if(branchBool == false){
                    newStr[index] = numbers[i];
                    index++;
                    branchBool = true;
                }else{
                    branchBool = false;
                }
            }
           StringBuffer bfs = new StringBuffer();
           for(String nstr : newStr ){
               if(bfs.length() >0 ){
                   if(nstr!=null && !nstr.equals("null")){
                       bfs.append(","+nstr);
                   }
               }else{
                   bfs.append(nstr);
               }
           }
            ucpVoipVoiceBranch.setCalledNumbers( bfs.toString() );
            ucpVoipVoiceMapper.updateByEntity( ucpVoipVoice );
            return ucpVoipVoiceMapper.updateByEntity( ucpVoipVoiceBranch );

        }

    }

    public Map saveVoipVoiceTask(JSONObject jsonObject) {
        Map map= new HashMap();
        UcpVoipVoiceVo ucpVoipVoiceVo = new UcpVoipVoiceVo();
        BeanUtils.copyProperties(jsonObject, ucpVoipVoiceVo);
        if(ucpVoipVoiceVo.getCalledNumbers()==null || ucpVoipVoiceVo.getCalledNumbers().equals("")){
            String numberList = String.valueOf(jsonObject.get( "numberList" ));
            if(numberList!=null && !numberList.equals("")){
                numberList = numberList.replace("[","");
                numberList = numberList.replace("]","");
                ucpVoipVoiceVo.setCalledNumbers( numberList );
            }
        }
        String uuid =  String.valueOf(jsonObject.get("uuid"));
        String promulgator =String.valueOf(jsonObject.get("promulgator"));
        if(promulgator==null || promulgator.equals("null") || promulgator.equals("")){
            map.put("result_code","1001");
            map.put("result_text","promulgator参数为空");
            return map;
        }
        if(uuid==null || uuid.equals("null") || uuid.equals("")){
            map.put("result_code","1001");
            map.put("result_text","uuid参数为空");
            return map;
        }
        String publishTime =String.valueOf(jsonObject.get("publishTime"));
        String publishFilePath =String.valueOf(jsonObject.get("publishFilePath"));
        String publishWay =String.valueOf(jsonObject.get("publishWay"));
        String result =String.valueOf(jsonObject.get("result"));
        String successSum =String.valueOf( jsonObject.get("successSum") );
        String failedSum = String.valueOf(jsonObject.get("failedSum"));
        Integer IsuccessSum = successSum!=null && !successSum.equals("null")  ? Integer.parseInt( successSum ) : 0;
        Integer IfailedSum = failedSum!=null && !failedSum.equals("null") ? Integer.parseInt( failedSum ) : 0;
        ucpVoipVoiceVo.setSuccessSum( IsuccessSum  );
        ucpVoipVoiceVo.setFailedSum( IfailedSum );
        String groupList = String.valueOf(jsonObject.get( "groupList" ));
        if(groupList!=null && !groupList.equals("")){
            groupList = groupList.replace("[","");
            groupList = groupList.replace("]","");
            ucpVoipVoiceVo.setGroupList( groupList );
        }
        if(result == null || result.equals("null")){
            ucpVoipVoiceVo.setResult( 0 );
        }else{
            Integer integerResult = Integer.valueOf(result);
            ucpVoipVoiceVo.setResult( integerResult );
        }
        ucpVoipVoiceVo.setUuid(uuid);
        ucpVoipVoiceVo.setPromulgator( promulgator );
        ucpVoipVoiceVo.setPublishTime( publishTime );
        ucpVoipVoiceVo.setPublishFilePath( publishFilePath );
        ucpVoipVoiceVo.setPublishWay( publishWay );
        Integer ts = this.saveUcpVoipVoice(  ucpVoipVoiceVo );
        boolean bool = SqlHelper.retBool(ts);
        if(bool){
            Map topicMap = new HashMap();
            topicMap.put("type","VoipVoiceTask" );
            topicMap.put("uuid",uuid );
            topicMap.put("promulgator",promulgator);
            topicMap.put("publishTime",publishTime);
            topicMap.put("publishWay",publishWay);
            topicMap.put("successSum",successSum);
            topicMap.put("failedSum",failedSum);
            topicMap.put("groupList",groupList);
            topicMap.put("failedSum",failedSum);
            topicMap.put("result",result);
            Object json = JSONArray.toJSON(  topicMap );
            System.out.println(json.toString());
            //操作成功，开始发MQ数据
            jmsTemplate.convertAndSend(topic,json.toString());
        }
        if(bool){
            map.put("result_code","0");
            map.put("result_text","操作成功");
        }else{
            map.put("result_code","1001");
            map.put("result_text","参数错误");
        }
        return map;
    }



    @Override
    public List queryVoipVoiceList(Map map) {
        //先根据条件查询出父数据
        List<UcpVoipVoice> list =ucpVoipVoiceMapper.queryVoipVoiceList( map );

        // wsy 20190527 从结果中将带_数字的 无效行去掉
        List<UcpVoipVoice> listReturn = new ArrayList<UcpVoipVoice>();
        for(int index = 0; index < list.size(); index++){
            UcpVoipVoice item = list.get(index);
            if(item.getUuid().indexOf("_") < 0){
                listReturn.add(item);
            }
        }
        return listReturn;
    }

    @Override
    public List queryVoipVoiceList(String promulgator, String publishStartTime, String publishEndTime) {
        List<UcpVoipVoice> list =ucpVoipVoiceMapper.queryVoipVoiceList( promulgator , publishStartTime , publishEndTime );

        // wsy 20190527 从结果中将带_数字的 无效行去掉
        List<UcpVoipVoice> listReturn = new ArrayList<UcpVoipVoice>();
        for(int index = 0; index < list.size(); index++){
            UcpVoipVoice item = list.get(index);
            if(item.getUuid().indexOf("_") < 0){
                listReturn.add(item);
            }
        }
        return listReturn;
    }

    public List queryVoipVoiceRecordList(JSONObject jsonObject){
       return ucpVoipVoiceRecordService.queryVoipVoiceRecordList(jsonObject);
    }
}
